from rest_framework import serializers
from decimal import Decimal
import logging, json, datetime
from django_redis import get_redis_connection

from users.models import CustomerUser, User, Level
from merchants.models import *
from goods.models import *
from activities.models import *
from orders.models import *
from vouchers.models import *
from django.db.models import Count, Sum, Max, Min, Avg
from cashbonus.models import *
from equity_mall.utils.express_utils import KuaiDi100

logger = logging.getLogger('django')


class LevelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ['id', 'prov_name', 'city_name', 'district_name', 'branch_name']


class CustomerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    realname = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CustomerUser
        fields = ['id', 'realname', 'mobile', 'level_name', 'create_time', 'point']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_realname(self, obj):
        try:
            realname = obj.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''


class CustomerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_offline_str = serializers.CharField(source='get_is_offline_display', read_only=True)
    openid = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)
    realname = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    idcode = serializers.SerializerMethodField(read_only=True)
    ali_user_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUser
        fields = ['id', 'username', 'realname', 'mobile', 'level', 'create_time', 'is_offline_str', 'openid', 'avatar',
                  'obtain_point', 'use_point', 'order_num', 'company_user', 'ali_user_id', 'idcode']

    def get_company_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_openid(self, obj):
        try:
            return obj.old_openid
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data

    def get_realname(self, obj):
        try:
            realname = obj.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_idcode(self, obj):
        try:
            return f'{obj.idcode[:6]}****{obj.idcode[-3:]}'
        except:
            return ''

    def get_ali_user_id(self, obj):
        try:
            return f'{obj.ali_user_id[:4]}****{obj.ali_user_id[-4:]}'
        except:
            return ''


class CustomerUserPointRecordModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    business_type_str = serializers.CharField(source='get_business_type_display', read_only=True)

    class Meta:
        model = PointRecord
        fields = ['id', 'create_time', 'operate_type_str', 'business_type_str', 'point', 'point_balance', 'order_id']


class OrderGoodsModelSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    goods_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ['id', 'count', 'point', 'merchant', 'default_image', 'goods_name', 'price', 'level_name', 'goods_id']

    def get_level_name(self, obj):
        try:
            if obj.launched_goods:
                return obj.launched_goods.level.name
            else:
                return ''
        except:
            return ''

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except:
            return ''

    def get_goods_name(self, obj):
        try:
            return obj.goods.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        try:
            merchant = obj.merchant
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
        except:
            pass
        return data


class ManagerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    nickname = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level_name', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'level_id', 'role_id']

    def get_nickname(self, obj):
        try:
            nickname = obj.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class ManagerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    create_user_nickname = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    nickname = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'distributed_point_num', 'level_id', 'role_id', 'avatar',
                  'create_user_nickname']

    def get_nickname(self, obj):
        try:
            nickname = obj.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_create_user_nickname(self, obj):
        try:
            nickname = obj.create_user.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account')


class MerchantListModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level_name', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'create_time', 'short_name', 'is_enter_auth', 'is_mall_str', 'is_mall')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
            if not check_merhant_channel:
                return 0
            else:
                return 1
        else:
            return 0

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantImage
        fields = ['id', 'image']


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_category_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = MerchantImageSerializer(many=True)
    identification_number = serializers.SerializerMethodField(read_only=True)
    account_number = serializers.SerializerMethodField(read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)
    mall_applyment = serializers.SerializerMethodField(read_only=True)
    managerName = serializers.SerializerMethodField(read_only=True)
    managermobile = serializers.SerializerMethodField(read_only=True)
    account_name = serializers.SerializerMethodField(read_only=True)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'store_address', 'managerName', 'managermobile', 'account_name',
                  'account_bank', 'account_number', 'identification_number', 'create_time', 'store_header_copy',
                  'short_name', 'open_work_time', 'close_work_time', 'merchantimage_set', 'store_logo_copy', 'business_category_id',
                  'business_category_name', 'longitude', 'latitude', 'prov_name', 'city_name', 'district_name', 'prov_code',
                  'city_code', 'district_code', 'merchant_desc', 'is_online', 'is_enter_auth', 'mall_applyment', 'is_mall_str', 'is_mall')

    def get_account_name(self, obj):
        try:
            account_name = obj.account_name
            return f'{account_name.replace(account_name[-2], "*", 1)}'
        except:
            return ''

    def get_managerName(self, obj):
        try:
            managerName = obj.managerName
            return f'{managerName.replace(managerName[-2], "*", 1)}'
        except:
            return ''

    def get_managermobile(self, obj):
        try:
            managermobile = obj.managermobile
            return f'{managermobile[:3]}****{managermobile[-4:]}'
        except:
            return ''

    def get_mall_applyment(self, obj):
        data = {}
        data['is_mall'] = obj.is_mall
        data['is_mall_str'] = obj.get_is_mall_display()
        data['create_time'] = ''
        data['contract'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['audit_time'] = ''
        data['verify_state'] = ''
        data['verify_state_str'] = ''
        data['verify_user'] = ''
        data['verify_time'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        try:
            mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
            if mall_applyment:
                data['reject_reason'] = mall_applyment.reject_reason
                data['create_time'] = mall_applyment.create_time.strftime("%Y-%m-%d %H:%M:%S")
                data['contract'] = mall_applyment.contract.url
                data['applyment_state'] = mall_applyment.applyment_state
                data['applyment_state_str'] = mall_applyment.get_applyment_state_display()
                data['verify_state'] = mall_applyment.verify_state
                data['verify_state_str'] = mall_applyment.get_verify_state_display()
                if mall_applyment.verify_user:
                    data['verify_user'] = mall_applyment.verify_user.nickname
                data['sign_url'] = mall_applyment.sign_url.url
                data['audit_time'] = mall_applyment.audit_time.strftime("%Y-%m-%d %H:%M:%S")
                data['verify_time'] = mall_applyment.verify_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            # check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
            # if not check_merhant_channel:
            if obj.channel_id != 3:
                return 0
            else:
                return 1
        else:
            return 0

    def get_identification_number(self, obj):
        try:
            return f'{obj.identification_number[:6]}****{obj.identification_number[-3:]}'
        except:
            return ''

    def get_account_number(self, obj):
        try:
            return f'{obj.account_number[:4]}****{obj.account_number[-4:]}'
        except:
            return ''

    def get_business_category_name(self, obj):
        try:
            return obj.business_category.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class MerchantEnterModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level = serializers.SerializerMethodField(read_only=True)
    manageruser = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEnter
        fields = ('id', 'create_time', 'level', 'manageruser')

    def get_manageruser(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'order_species', 'order_species_str')

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class GoodsModifyApplymentModelSerializer(serializers.ModelSerializer):

    desc_detail = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)
    applyment_type_str = serializers.CharField(source='get_applyment_type_display', read_only=True)

    class Meta:
        model = GoodsModifyApplyment
        fields = ('id', 'name', 'applyment_type', 'caption', 'desc_detail', 'price', 'market_price', 'default_image', 'goodsimage_set',
                  'manufacturer', 'specifications', 'applyment_type_str', 'company_user')

    def get_company_user(self, obj):
        try:
            return f'{obj.companyuser.nickname}({obj.companyuser.level.name})'
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        try:
            return json.loads(obj.image_array)
        except:
            return obj.image_array


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)
    reject_reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant_name', 'manufacturer', 'specifications', 'caption', 'goodsimage_set', 'desc_detail',
                  'market_price', 'merchant_id', 'applyment', 'reject_reason', 'order_species', 'order_species_str')

    def get_reject_reason(self, obj):
        try:
            if obj.is_launched == 3:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=3).last()
                return applyment.reject_reason
            else:
                return ''
        except:
            return ''

    def get_applyment(self, obj):
        try:
            if obj.is_launched == 2:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=1).first()
                return GoodsModifyApplymentModelSerializer(applyment).data
            else:
                return {}
        except:
            return {}

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''


class LaunchedGoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    goodsinfo = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'create_time', 'point', 'goodsinfo', 'sales', 'level_name', 'is_launched', 'is_launched_str', 'stock')

    def get_goodsinfo(self, obj):
        data = {}
        data['default_image'] = ''
        data['name'] = ''
        data['category'] = ''
        data['equityID'] = ''
        data['merchant_name'] = ''
        data['sales'] = ''
        data['remain_stock'] = ''
        try:
            goods = obj.goods
            data['default_image'] = goods.default_image.url
            data['name'] = goods.name
            data['category'] = goods.category.name
            data['equityID'] = goods.equityID
            data['merchant_name'] = goods.merchant.name
            data['sales'] = goods.sales
            data['remain_stock'] = goods.remain_stock
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class ActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_name = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ('id', 'create_time', 'activity_name', 'point', 'state', 'state_str', 'received_time', 'companyuser_nickname', 'level_name')

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.companyuser.level.name
        except:
            return ''


class ActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_name = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    companyuser_level = serializers.SerializerMethodField(read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    customeruser_level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ('id', 'create_time', 'activity_name', 'point', 'state', 'state_str', 'received_time', 'companyuser_nickname', 'companyuser_level',
                  'customeruser_realname', 'customeruser_level')

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_companyuser_level(self, obj):
        try:
            level = obj.companyuser.level
            return f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('-None', '')
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_customeruser_level(self, obj):
        try:
            level = obj.customer_user.level
            return f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('-None', '')
        except:
            return ''


class ActivityListSerializer(serializers.ModelSerializer):

    available_area = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    remain_point = serializers.SerializerMethodField(read_only=True)
    progress = serializers.SerializerMethodField(read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)

    class Meta:
        model = Activity
        fields = ('id', 'name', 'available_area', 'available_begin_time', 'available_end_time', 'max_point', 'distributed_point', 'remain_point', 'progress', 'activity_state',
                  'activity_state_str')

    def get_available_area(self, obj):
        try:
            level = obj.level
            return f'{level.prov_name}{level.city_name}{level.district_name}{level.branch_name}'.replace('None', '')
        except:
            return ''

    def get_remain_point(self, obj):
        try:
            return obj.max_point - obj.distributed_point
        except:
            return '0'

    def get_progress(self, obj):
        try:
            return f'{(obj.distributed_point / obj.max_point * 100).quantize(Decimal("0.00"))}%'
        except:
            return '0%'


class UserInfoSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    dimensionality_choices = serializers.SerializerMethodField(read_only=True)
    is_admin = serializers.SerializerMethodField(read_only=True)
    map_key = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'header', 'level_id', 'level_name', 'level', 'role_name', 'dimensionality_choices', 'is_admin',
                  'map_key')

    def get_map_key(self, obj):
        return '5PLBZ-KIZC6-NCKSH-MOPXS-QP6OK-M4BIO'

    def get_is_admin(self, obj):
        try:
            if obj.role_id == 1:
                return 1
            else:
                if obj.level.level == 1:
                    return 1
                else:
                    return 0
        except:
            return 0

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_dimensionality_choices(self, obj):
        try:
            dic1 = {
                0: {0: '信翔'},
                1: {1: '省公司'},
                2: {2: '市公司'},
                3: {3: '区县'},
                4: {4: '网点'},
            }
            level = obj.level.level
            data = []
            for i in range(level, 5):
                data.append(dic1[i])
            return data
        except:
            return []

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    success_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    customer_user_mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_point', 'success_time', 'total_price', 'level_name',
                  'customer_user_mobile', 'use_time', 'order_species', 'order_species_str', 'payment_time']

    def get_customer_user_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return f'{obj.level.name}(分店)'
        except:
            return '商家自营'


class OrderFundTransModelSerializer(serializers.ModelSerializer):

    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'trans_date', 'exchange_amount', 'status', 'status_str', 'identity', 'name', 'pay_fund_order_id', 'sub_msg']


class OrderAddressModelSerializer(serializers.ModelSerializer):

    mobile = serializers.SerializerMethodField(read_only=True)
    receiver = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']

    def get_mobile(self, obj):
        try:
            mobile = obj.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_receiver(self, obj):
        try:
            receiver = obj.receiver
            return receiver.replace(receiver[-2], '*', 1)
        except:
            return ''


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    deliverystatus = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_deliverystatus(self, obj):
        try:
            if obj.deliverystatus in [0, 1, 5, 2, 6]:
                redis_conn = get_redis_connection("express_number")
                express_number_flag = redis_conn.get("express_number_%s" % obj.express_number)
                if not express_number_flag:
                    redis_conn.setex('express_number_%s' % obj.express_number, 21600, 1)
                    order = ExpressOrderRelevance.objects.filter(express_id=obj.id).first()
                    phone = OrderAddress.objects.filter(order_id=order.order_id).first()
                    if phone:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number, phone.mobile[-4:])
                    else:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number)
                    if result['status'] == '200':
                        obj.deliverystatus = result['state']
                        obj.save()
                        if obj.deliverystatus == 3:
                            try:
                                order = obj.order
                                user = order.user
                            except:
                                pass
                        for i in result['data']:
                            plan_data = {}
                            plan_data['express_id'] = obj.id
                            plan_data['create_time'] = i['time']
                            plan_data['remark'] = i['context']
                            ExpressPlan.objects.get_or_create(defaults=plan_data, create_time=i['time'], express_id=obj.id)
                        if str(obj.deliverystatus) == "3":
                            try:
                                sign_time = ExpressPlan.objects.filter(express_id=obj.id).aggregate(Max('create_time'))['create_time__max']
                                obj.sign_time = sign_time
                                obj.save()
                            except:
                                pass
                    else:
                        obj.deliverystatus = 9
                        obj.save()
                        ExpressPlan.objects.create(remark=result['message'], create_time=datetime.datetime.now(), express_id=obj.id)
            return obj.deliverystatus
        except:
            return obj.deliverystatus

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # success_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    companyuser = serializers.SerializerMethodField(read_only=True)
    orderfundtrans_set = OrderFundTransModelSerializer(many=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    bill = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state_str', 'ordergoods_set', 'total_point', 'customer_user', 'companyuser',
                  'total_price', 'realpay_amount', 'discount_amount', 'orderfundtrans_set', 'state', 'bill', 'orderaddress', 'express_info',
                  'payment_time']

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount - obj.total_point/100).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount - obj.total_point/100).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['level'] = ''
        data['mobile'] = ''
        data['id'] = ''
        data['merchant'] = []
        data['is_merchant'] = 0
        try:
            customer_user = obj.customer_user
            realname = customer_user.realname
            mobile = customer_user.mobile
            level = customer_user.level
            data['id'] = customer_user.id
            data['realname'] = realname.replace(realname[-2], '*', 1)
            data['mobile'] = f'{mobile[:3]}****{mobile[-4:]}'
            if level:
                data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            merchant_set = Merchant.objects.filter(managermobile=customer_user.mobile)
            if merchant_set:
                data['is_merchant'] = 1
                merchant_list = []
                for merchant in merchant_set:
                    level = merchant.level
                    merchant_data = {}
                    merchant_data['id'] = merchant.id
                    merchant_data['business_no'] = merchant.wyfMerchantID
                    merchant_data['short_name'] = merchant.short_name
                    merchant_data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
                    merchant_list.append(merchant_data)
                data['merchant'] = merchant_list
            return data
        except Exception as e:
            pass
        return data

    def get_companyuser(self, obj):
        data = {}
        data['nickname'] = ''
        data['level'] = ''
        data['success_time'] = ''
        try:
            goodscoupons = obj.goodscoupons_set.all().order_by('-use_time').first()
            data['success_time'] = goodscoupons.use_time.strftime("%Y-%m-%d %H:%M:%S")
            companyuser = goodscoupons.use_user
            level = companyuser.level
            nickname = companyuser.nickname
            mobile = f'{companyuser.mobile[:3]}****{companyuser.mobile[-4:]}'
            data['nickname'] = f"{nickname.replace(nickname[-2], '*', 1)}({mobile})"
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            return data
        except:
            pass
        return data

    def get_bill(self, obj):
        data = {}
        data['id'] = ''
        data['receipts_time'] = ''
        data['bill_state'] = ''
        data['bill_state_str'] = ''
        data['settlement_time'] = ''
        data['settlement_record_id'] = ''
        try:
            bill = obj.bill
            data['id'] = bill.id
            data['receipts_time'] = bill.receipts_time.strftime("%Y-%m-%d")
            data['bill_state'] = bill.bill_state
            data['bill_state_str'] = bill.get_bill_state_display()
            data['settlement_time'] = bill.settlement_time.strftime("%Y-%m-%d")
            data['settlement_record_id'] = bill.settlement_record_id
        except:
            pass
        return data


class AliDiscountCouponListModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    coupon_status = serializers.SerializerMethodField(read_only=True)
    max_number = serializers.SerializerMethodField(read_only=True)
    remain_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'coupon_way', 'coupon_way_str', 'template_id']

    def get_remain_number(self, obj):
        if obj.coupon_way == 5:
            return obj.remain_number
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.id).first()
            return alidiscountcouponlevel.p_remain_number
        except:
            return 0

    def get_max_number(self, obj):
        if obj.coupon_way == 5:
            return obj.max_number
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.id).first()
            return alidiscountcouponlevel.p_max_number
        except:
            return 0

    def get_coupon_status(self, obj):
        try:
            now_date = datetime.datetime.now()
            if obj.coupon_status in [1, 4]:
                if obj.publish_end_time < now_date:
                    obj.coupon_status = 2
                    obj.save()
                    return 2
            # elif obj.coupon_status == 3:
            #     if obj.publish_start_time < now_date:
            #         obj.coupon_status = 1
            #         obj.save()
            #         return 1
            return obj.coupon_status
        except:
            return obj.coupon_status

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''


class AliDiscountCouponChannelCommonVoucherModelSerializer(serializers.ModelSerializer):

    discount_type_str = serializers.CharField(source='get_discount_type_display', read_only=True)
    bankcard_type_str = serializers.CharField(source='get_bankcard_type_display', read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    join_limit_by_user = serializers.SerializerMethodField(read_only=True)
    join_limit_by_bay = serializers.SerializerMethodField(read_only=True)
    distributed_limit_by_time_rules = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponChannelCommonVoucher
        fields = ['id', 'discount_type', 'discount_type_str', 'bankcard_type', 'bankcard_type_str', 'usetime_type', 'principal_name',
                  'join_limit_by_user', 'join_limit_by_bay', 'distributed_limit_by_time', 'distributed_limit_by_time_rules']

    def get_distributed_limit_by_time_rules(self, obj):
        data = []
        try:
            alidiscountcoupondistributedlimit_set = obj.alidiscountcoupondistributedlimit_set.all()
            for alidiscountcoupondistributedlimit in alidiscountcoupondistributedlimit_set:
                week_day_dict = {
                    '0': '周一',
                    '1': '周二',
                    '2': '周三',
                    '3': '周四',
                    '4': '周五',
                    '5': '周六',
                    '6': '周日',
                }
                weeks = ''
                for key,value in week_day_dict.items():
                    if key in alidiscountcoupondistributedlimit.weeks:
                        weeks += f'、{value}'
                data.append({
                    "weeks": f'每周 {weeks[1:]}',
                    "enable_time": f'{alidiscountcoupondistributedlimit.start_enable_time.strftime("%H:%M:%S")}-{alidiscountcoupondistributedlimit.end_enable_time.strftime("%H:%M:%S")}'
                })
        except:
            pass
        return data

    def get_usetime_type(self, obj):
        try:
            if obj.usetime_type == 2:
                return f'固定时间段{obj.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif obj.usetime_type == 3:
                return f'领取后立即生效有效时间{obj.invalid_day}天'
            else:
                return f'领取后次日凌晨生效有效时间{obj.invalid_day}天'
        except:
            return ''

    def get_join_limit_by_user(self, obj):
        try:
            if obj.join_limit_by_user == 1:
                return f'活动期间每个用户可参与{obj.join_limit_by_user_count}次'
            else:
                return '不限制'
        except:
            return ''

    def get_join_limit_by_bay(self, obj):
        try:
            if obj.join_limit_by_bay == 1:
                return f'每个用户每日可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 2:
                return f'每个用户每月可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 4:
                return f'每个用户每周可参与{obj.join_limit_by_bay_count}次'
            else:
                return '不限制'
        except:
            return ''


class AliDiscountCouponRetrieveModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    alidiscountcouponchannelcommonvoucher = AliDiscountCouponChannelCommonVoucherModelSerializer()
    level = LevelModelSerializer()
    merchant_list = serializers.SerializerMethodField(read_only=True)
    platform = serializers.SerializerMethodField(read_only=True)
    can_remain_number = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    max_number = serializers.SerializerMethodField(read_only=True)
    remain_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'alidiscountcouponchannelcommonvoucher', 'level',
                  'is_union', 'is_white', 'available_merchants', 'coupon_way', 'coupon_way_str', 'activity_description', 'merchant_list',
                  'create_time', 'template_id', 'platform', 'publish_end_time', 'publish_start_time', 'transaction_minimum', 'amount',
                  'is_need_auth', 'can_remain_number']

    def get_remain_number(self, obj):
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.id).first()
            return alidiscountcouponlevel.p_remain_number
        except:
            return 0

    def get_max_number(self, obj):
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.id).first()
            return alidiscountcouponlevel.p_max_number
        except:
            return 0

    def get_can_remain_number(self, obj):
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.id).first()
            return alidiscountcouponlevel.remain_number
        except:
            return 0

    def get_platform(self, obj):
        try:
            platform = obj.platform
            return f'{platform.name}({platform.mchid})'
        except:
            return ''

    def get_merchant_list(self, obj):
        data = []
        try:
            alidiscountcouponmerchant_set = obj.alidiscountcouponmerchant_set.all()
            if alidiscountcouponmerchant_set:
                alidiscountcouponmerchant_set = alidiscountcouponmerchant_set[:6]
                for alidiscountcouponmerchant in alidiscountcouponmerchant_set:
                    merchant = alidiscountcouponmerchant.merchant
                    data.append(f'{merchant.short_name}({merchant.wyfMerchantID})')
        except:
            pass
        return data

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''


class AliDiscountCouponLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)
    is_update = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number',
                  'activity_name', 'p_max_number', 'p_take_number', 'p_remain_number', 'p_wait_number', 'p_unclaimed_number', 'p_use_number', 'is_update']

    def get_is_update(self, obj):
        try:
            user = self.context.get('user', None)
            if obj.level_id == user.level_id:
                return 0
            else:
                return 1
        except:
            return 0

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.activity_name
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponLevelRetrieveModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    can_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number', 'can_number']

    def get_can_number(self, obj):
        data = {}
        data['max_number'] = 0
        data['min_number'] = 0
        try:
            user = self.context.get('user', None)
            alidiscountcouponlevel = AliDiscountCouponLevel.objects.filter(level_id=user.level_id, activity_id=obj.activity_id).first()
            data['max_number'] = obj.max_number + alidiscountcouponlevel.remain_number
            data['min_number'] = obj.take_number
        except:
            pass
        return data

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_distributed', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'coupon_type', 'coupon_type_str', 'level_name']

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    payout_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'mobile', 'status', 'status_str', 'customeruser_realname', 'gmt_use', 'gmt_distributed', 'gmt_undo', 'payout_info', 'activity_info', 'order_id']

    def get_activity_info(self, obj):
        data = {}
        data['activity_name'] = ''
        data['floor_amount'] = ''
        data['publish_time'] = ''
        data['usetime_type'] = ''
        data['coupon_type'] = ''
        data['coupon_type_str'] = ''
        try:
            activity = obj.alidiscountcoupon
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_type'] = activity.coupon_type
            data['floor_amount'] = activity.floor_amount
            data['publish_time'] = f'{activity.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data['activity_name'] = activity.activity_name
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            if channelcommonvoucher.join_limit_by_user == 1:
                data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
            else:
                data['join_limit_by_user'] = '不限制'
            if channelcommonvoucher.join_limit_by_bay == 1:
                data['join_limit_by_bay'] = f'每个用户每日可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            if channelcommonvoucher.join_limit_by_bay == 2:
                data['join_limit_by_bay'] = f'每个用户每月可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            elif channelcommonvoucher.join_limit_by_bay == 4:
                data['join_limit_by_bay'] = f'每个用户每周可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            else:
                data['join_limit_by_bay'] = '不限制'
        except:
            pass
        return data

    def get_payout_info(self, obj):
        data = {}
        data['alidiscountcoupon_id'] = ''
        data['level_name'] = ''
        data['companyuser_nickname'] = ''
        data['gmt_create'] = ''
        try:
            data['alidiscountcoupon_id'] = obj.alidiscountcoupon_id
            data['level_name'] = obj.level.name
            nickname = obj.companyuser.nickname
            data['companyuser_nickname'] = nickname.replace(nickname[-2], '*', 1)
            data['gmt_create'] = obj.gmt_create.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data

    def get_customeruser_realname(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''


class MerchantBillListModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    account_info = serializers.SerializerMethodField(read_only=True)
    week_day = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'account_info', 'settlement_time', 'week_day',
                  'order_count', 'bill_type_str', 'bill_type']

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_week_day(self, obj):
        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期日',
        }
        day = obj.receipts_time.weekday()
        return week_day_dict[day]

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['merchant_id'] = ''
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['wyfMerchantID'] = merchant.wyfMerchantID
            data['level_name'] = level.name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['merchant_id'] = merchant.id
        except:
            pass
        return data

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantBillRetrieveModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    account_info = serializers.SerializerMethodField(read_only=True)
    # payable_amount = serializers.SerializerMethodField(read_only=True)
    settlement_info = serializers.SerializerMethodField(read_only=True)
    fail_reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'settlement_time', 'order_count', 'account_info',
                  'settlement_info', 'fail_reason']

    def get_fail_reason(self, obj):
        return ''

    def get_settlement_info(self, obj):
        data = []
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                merchantsettlementrecord_data = {}
                merchantsettlementrecord = merchantbillsettlementrecord.settlement_record
                merchantsettlementrecord_data['settlement_time'] = merchantsettlementrecord.settlement_time.strftime('%Y-%m-%d')
                merchantsettlementrecord_data['settlement_id'] = merchantsettlementrecord.id
                merchantsettlementrecord_data['settlement_amount'] = merchantsettlementrecord.amount
                merchantsettlementrecord_data['status'] = merchantsettlementrecord.status
                merchantsettlementrecord_data['status_str'] = merchantsettlementrecord.get_status_display()
                data.append(merchantsettlementrecord_data)
        except:
            pass
        return data

    # def get_payable_amount(self, obj):
    #     try:
    #         bill_state = obj.bill_state
    #         if bill_state == 3:
    #             return obj.settlement_record.amount
    #         else:
    #             return 0
    #     except:
    #         return 0

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level'] = ''
        data['merchant_id'] = ''
        try:
            data['merchant_name'] = obj.merchant.name
            data['wyfMerchantID'] = obj.merchant.wyfMerchantID
            data['merchant_id'] = obj.merchant_id
            level = obj.merchant.level
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name', 'icon']


class MerchantBusinessCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantBusinessCategory
        fields = ['id', 'name']


class EnterLvelModelSerializer(serializers.ModelSerializer):

    contact = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Level
        fields = ['id', 'city_name', 'district_name', 'branch_name', 'account', 'contact']

    def get_contact(self, obj):
        data = {}
        merchant = self.context.get('merchant', None)
        data['managerName'] = merchant.managerName
        data['managermobile'] = merchant.managermobile
        try:
            enterlevel = MerchantEnter.objects.filter(level_id=obj.id, merchant_id=merchant.id).first()
            if enterlevel:
                data['managerName'] = enterlevel.managerName
                data['managermobile'] = enterlevel.managermobile
        except:
            pass
        return data


class ChannelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Channel
        fields = ['id', 'mchid', 'name']


class CashActivityListModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    rule = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    remain_amount = serializers.SerializerMethodField(read_only=True)
    max_amount = serializers.SerializerMethodField(read_only=True)
    activity_state = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivity
        fields = ['id', 'name', 'activity_type', 'activity_type_str', 'activity_state', 'activity_state_str', 'max_amount', 'remain_amount', 'available_begin_time', 'available_end_time', 'rule']

    def get_activity_state(self, obj):
        try:
            now_date = datetime.datetime.now()
            if obj.activity_state != 4 and obj.available_end_time < now_date:
                obj.activity_state = 4
                obj.save()
                return 4
            return obj.activity_state
        except:
            return obj.activity_state

    def get_rule(self, obj):
        try:
            if obj.activity_type == 1:
                return f'{obj.min_distributed_amount}-{obj.max_distributed_amount}'
            else:
                cashactivityrule_set = obj.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'{cashactivityrule.amount},'
                return result[:-1]
        except:
            return ''

    def get_remain_amount(self, obj):
        try:
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.id).first()
            return cashactivitylevel.p_remain_amount
        except:
            return 0

    def get_max_amount(self, obj):
        try:
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.id).first()
            return cashactivitylevel.p_max_amount
        except:
            return 0


class CashActivityRuleModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = CashActivityRule
        fields = ['id', 'amount', 'probability']


class CashActivityRetrieveModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    rule = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level = serializers.SerializerMethodField(read_only=True)
    can_remain_amount = serializers.SerializerMethodField(read_only=True)
    remain_amount = serializers.SerializerMethodField(read_only=True)
    max_amount = serializers.SerializerMethodField(read_only=True)
    cashactivityrule_set = CashActivityRuleModelSerializer(many=True)

    class Meta:
        model = CashActivity
        fields = ['id', 'name', 'activity_type', 'activity_type_str', 'activity_state', 'activity_state_str', 'max_amount', 'remain_amount', 'available_begin_time', 'available_end_time', 'rule',
                  'activity_description', 'create_time', 'level', 'can_remain_amount', 'cashactivityrule_set', 'is_max_amount_by_day', 'is_max_amount_by_user_by_day', 'is_max_amount_by_user',
                  'is_max_amount_by_customeruser', 'max_amount_by_day', 'max_amount_by_user_by_day', 'max_amount_by_user', 'max_amount_by_customeruser', 'is_need_auth',
                  'is_wechat', 'is_white', 'is_limit_white', 'white_accout', 'is_merchant', 'repeat_business_no_count']

    def get_can_remain_amount(self, obj):
        try:
            if obj.activity_type == 8:
                return obj.remain_amount
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.id).first()
            return cashactivitylevel.remain_amount
        except:
            return 0

    def get_remain_amount(self, obj):
        try:
            if obj.activity_type == 8:
                return obj.remain_amount
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.id).first()
            return cashactivitylevel.p_remain_amount
        except:
            return 0

    def get_max_amount(self, obj):
        try:
            if obj.activity_type == 8:
                return obj.max_amount
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.id).first()
            return cashactivitylevel.p_max_amount
        except:
            return 0

    def get_rule(self, obj):
        try:
            if obj.activity_type == 1:
                return f'{obj.min_distributed_amount}-{obj.max_distributed_amount}'
            else:
                cashactivityrule_set = obj.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'{cashactivityrule.amount},'
                return result[:-1]
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class CashActivityLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    is_update = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'activity_name', 'p_receive_amount', 'p_remain_amount', 'p_take_amount', 'p_max_amount', 'p_unclaimed_amount', 'is_auth', 'is_auth_str', 'is_update',
                  'remain_amount']

    def get_is_update(self, obj):
        try:
            user = self.context.get('user', None)
            if obj.level_id == user.level_id:
                return 0
            else:
                return 1
        except:
            return 0

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class CashActivityLevelRetrieveModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    can_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'max_amount', 'take_amount', 'remain_amount', 'unclaimed_amount', 'receive_amount', 'activity_name', 'can_amount']

    def get_can_amount(self, obj):
        data = {}
        data['max_amount'] = 0
        data['min_amount'] = 0
        try:
            user = self.context.get('user', None)
            cashactivitylevel = CashActivityLevel.objects.filter(level_id=user.level_id, cash_activity_id=obj.cash_activity_id).first()
            data['max_amount'] = obj.max_amount + cashactivitylevel.remain_amount
            data['min_amount'] = obj.take_amount
        except:
            pass
        return data

    def get_unclaimed_amount(self, obj):
        try:
            unclaimed_amount = obj.take_amount - obj.receive_amount
            return unclaimed_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return '网点'
            else:
                return '信翔'
        except:
            return ''


class CashActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    city_name = serializers.SerializerMethodField(read_only=True)
    district_name = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'mobile', 'state', 'state_str', 'received_time', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'activity_type', 'activity_type_str', 'level_name', 'amount', 'city_name', 'district_name', 'merchant']

    def get_merchant(self, obj):
        data = {}
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['level_name'] = ''
        data['is_white'] = ''
        try:
            white = CashActivityDataWhiteTable.objects.filter(activitydata_id=obj.id).first()
            if white:
                data['business_no'] = white.business_no
                data['is_white'] = str(white.is_white_table)
                if white.is_white_table == 0:
                    merchant = Merchant.objects.filter(wyfMerchantID=white.business_no).first()
                    data['merchant_name'] = merchant.name
                    data['level_name'] = merchant.level.name
        except:
            pass
        return data

    def get_city_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''

    def get_district_name(self, obj):
        try:
            return obj.level.district_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_activity_type_str(self, obj):
        try:
            return obj.cash_activity.get_activity_type_display()
        except:
            return ''

    def get_activity_type(self, obj):
        try:
            return obj.cash_activity.activity_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    city_name = serializers.SerializerMethodField(read_only=True)
    district_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'mobile', 'state', 'state_str', 'received_time', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'activity_type', 'activity_type_str', 'level_name', 'amount', 'expired_time', 'payment_no', 'cash_activity_id', 'return_msg', 'payeeFullName',
                  'city_name', 'district_name']

    def get_city_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''

    def get_district_name(self, obj):
        try:
            return obj.level.district_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_activity_type_str(self, obj):
        try:
            return obj.cash_activity.get_activity_type_display()
        except:
            return ''

    def get_activity_type(self, obj):
        try:
            return obj.cash_activity.activity_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''


class CashActivityLevelStatisticalModelSerializer(serializers.ModelSerializer):

    child_list = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    level_type = serializers.SerializerMethodField(read_only=True)
    amountData = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['level_name', 'level_type', 'p_max_amount', 'p_take_amount', 'p_remain_amount', 'amountData', 'child_list']

    def get_level_name(self, obj):
        return obj.level.name

    def get_level_type(self, obj):
        level = obj.level.level
        if level == 1:
            return '省公司'
        elif level == 2:
            return '市公司'
        elif level == 3:
            return '区县'
        elif level == 4:
            return '网点'
        else:
            return '信翔'

    def get_amountData(self, obj):
        data = [
            {"name": "已派发", "value": obj.p_take_amount},
            {"name": "剩余额度", "value": obj.p_remain_amount},
            {"name": "总额度", "value": obj.p_max_amount}
        ]
        return data

    def get_child_list(self, obj):
        level = obj.level
        if level.level == 1:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 2:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 3:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 4:
            return []
        else:
            return []


class CashActivityLevelTreeModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    child_list = serializers.SerializerMethodField(read_only=True)
    is_update = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'remain_amount', 'activity_name',
                  'p_receive_amount', 'p_remain_amount', 'p_take_amount', 'p_max_amount', 'p_unclaimed_amount', 'is_auth', 'is_auth_str',
                  'child_list', 'is_update']

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''

    def get_is_update(self, obj):
        try:
            user = self.context.get('user', None)
            if obj.level_id == user.level_id:
                return 0
            else:
                return 1
        except:
            return 0

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''

    def get_child_list(self, obj):
        level = obj.level
        user = self.context.get('user', None)
        if level.level == 1:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True, context={'user': user}).data
        elif level.level == 2:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True, context={'user': user}).data
        elif level.level == 3:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True, context={'user': user}).data
        elif level.level == 4:
            return []
        else:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=1)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True, context={'user': user}).data


class CashActivityLevelRecordModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    operation_type_str = serializers.CharField(source='get_operation_type_display', read_only=True)
    user_nickname = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CashActivityLevelRecord
        fields = ['id', 'level_name', 'operation_type', 'operation_type_str', 'amount', 'remain_amount', 'create_time', 'remark', 'user_nickname']

    def get_level_name(self, obj):
        try:
            return obj.activity_level.level.name
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.operation_type in [1, 3, 6]:
    #             return obj.amount
    #         else:
    #             return -obj.amount
    #     except:
    #         return ''

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class AliDiscountCouponMerchantModelSerializer(serializers.ModelSerializer):

    merchant = MerchantListModelSerializer()
    channel = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponMerchant
        fields = ['id', 'sub_mchid', 'merchant', 'channel_id', 'channel']

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''


class WaivePaymentActivityModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    is_repeat_str = serializers.CharField(source='get_is_repeat_display', read_only=True)
    activity_state = serializers.SerializerMethodField(read_only=True)
    join_number = serializers.SerializerMethodField(read_only=True)
    receive_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentActivity
        fields = ['id', 'activity_name', 'available_begin_time', 'available_end_time', 'desc', 'activity_state', 'activity_state_str', 'description',
                  'receive_amount', 'join_number', 'create_time', 'is_repeat', 'is_repeat_str']

    def get_receive_amount(self, obj):
        try:
            user = self.context.get('user', None)
            level = user.level
            if level.level == 0:
                queryset = WaivePaymentMerchant.objects.filter(payment_state=2).exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10])
            elif level.level == 1:
                queryset = WaivePaymentMerchant.objects.filter(level__prov_id=level.id, payment_state=2).exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10])
            elif level.level == 2:
                queryset = WaivePaymentMerchant.objects.filter(level__city_id=level.id, payment_state=2).exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10])
            elif level.level == 3:
                queryset = WaivePaymentMerchant.objects.filter(level__district_id=level.id, payment_state=2).exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10])
            else:
                queryset = WaivePaymentMerchant.objects.filter(level__branch_id=level.id, payment_state=2).exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10])
            if queryset:
                return queryset.aggregate(Sum('amount'))['amount__sum']
            else:
                return Decimal('0')
        except:
            return 0

    def get_join_number(self, obj):
        try:
            user = self.context.get('user', None)
            level = user.level
            if level.level == 0:
                queryset = WaivePaymentMerchant.objects.all()
            elif level.level == 1:
                queryset = WaivePaymentMerchant.objects.filter(level__prov_id=level.id)
            elif level.level == 2:
                queryset = WaivePaymentMerchant.objects.filter(level__city_id=level.id)
            elif level.level == 3:
                queryset = WaivePaymentMerchant.objects.filter(level__district_id=level.id)
            else:
                queryset = WaivePaymentMerchant.objects.filter(level__branch_id=level.id)
            return len(queryset.exclude(waivepaymentactivity_id__in=[2,3,4,5,6,7,8,10]))
        except:
            return 0

    def get_activity_state(self, obj):
        try:
            available_end_time = obj.available_end_time
            if available_end_time < datetime.datetime.now():
                obj.activity_state = 4
                obj.save()
            return obj.activity_state
        except:
            return obj.activity_state


class WaivePaymentAdvanceModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    activate_user = serializers.SerializerMethodField(read_only=True)
    trade_time_begin = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activate_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = WaivePaymentAdvance
        fields = ['id', 'create_time', 'activity_state', 'activity_state_str', 'remark',
                  'file', 'create_user', 'payment_state', 'payment_state_str', 'trade_time_begin',
                  'trade_time_end', 'activate_time', 'activate_user', 'name', 'operate_type', 'operate_type_str',
                  'join_number']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''

    def get_activate_user(self, obj):
        try:
            return obj.activate_user.nickname
        except:
            return ''


class WaivePaymentMerchantInfoModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'short_name', 'level']

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class WaivePaymentMerchantListModelSerializer(serializers.ModelSerializer):

    # create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    # received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = WaivePaymentMerchantInfoModelSerializer()
    # amount = serializers.SerializerMethodField(read_only=True)
    company_mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile', 'amount', 'merchant']

    def get_company_mobile(self, obj):
        try:
            mobile = obj.company_mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentMerchantRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    merchant = WaivePaymentMerchantInfoModelSerializer()
    company_mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'create_time', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile',
                  'received_time', 'payment_no', 'return_msg', 'partner_trade_no', 'account', 'name', 'payment_time',
                  'amount', 'merchant', 'activity_name', 'available_time']

    def get_company_mobile(self, obj):
        try:
            mobile = obj.company_mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.waivepaymentactivity.activity_name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            return f'{obj.waivepaymentactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.waivepaymentactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentOrderModelSerializer(serializers.ModelSerializer):

    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_type_str = serializers.CharField(source='get_trade_type_display', read_only=True)
    is_hit_str = serializers.CharField(source='get_is_hit_display', read_only=True)

    class Meta:
        model = WaivePaymentOrder
        fields = ['id', 'order_no', 'trade_no', 'trade_type', 'trade_type_str', 'rate_money',
                  'trade_money', 'settlement_money', 'trade_time_end', 'channel', 'is_hit', 'is_hit_str']


class CustomizeActivityListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    prize_type_array = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level_name', 'join_user_count',
                  'prize_type_array']

    def get_prize_type_array(self, obj):
        data = []
        try:
            PRIZE_TYPE_CHOICES = {
                "1": {"prize_type": 1, "prize_type_str": "支付宝代金券"},
                "2": {"prize_type": 2, "prize_type_str": "微信代金券"},
                "3": {"prize_type": 3, "prize_type_str": "微信鼓励金"},
                "5": {"prize_type": 5, "prize_type_str": "积分"},
                "6": {"prize_type": 6, "prize_type_str": "支付宝鼓励金"},
                "7": {"prize_type": 7, "prize_type_str": "商家券"},
            }
            prize_type = obj.prize_type
            for key,value in PRIZE_TYPE_CHOICES.items():
                if key in prize_type:
                    data.append(value)
        except:
            pass
        return data

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomizeActivityRulesListModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info']

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['max'] = ''
        data['remain'] = ''
        data['take'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2, 7]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = alidiscountcoupon.max_number
                data['remain'] = alidiscountcoupon.remain_number
                data['take'] = alidiscountcoupon.send_count
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = cashactivity.max_amount
                data['remain'] = cashactivity.remain_amount
                data['take'] = cashactivity.take_amount
        except:
            pass
        return data


class CustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    is_need_auth_str = serializers.CharField(source='get_is_need_auth_display', read_only=True)
    is_white_str = serializers.CharField(source='get_is_white_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    customizeactivityrules_set = CustomizeActivityRulesListModelSerializer(many=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level', 'join_user_count',
                  'is_need_auth', 'is_need_auth_str', 'lucky_count_by_user', 'activity_description', 'customizeactivityrules_set',
                  'is_white', 'is_white_str']

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level_name']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_customercser_mobile(self, obj):
        try:
            mobile = obj.user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
        except:
            pass
        return data


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_form = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level', 'business_form', 'return_msg']

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level(self, obj):
        data = {}
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            level = obj.level
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_customercser_mobile(self, obj):
        try:
            if obj.user:
                mobile = obj.user.mobile
                return f'{mobile[:3]}****{mobile[-4:]}'
            else:
                mobile = obj.customeruservice.customeruser.mobile
                return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class MerchantSettlementRecordListModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_time = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_time', 'merchant', 'level_name', 'is_bind',
                  'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_time(self, obj):
        data = ''
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                data += f"{merchantbillsettlementrecord.bill.receipts_time.strftime('%Y-%m-%d')},"
        except:
            pass
        if ',' in data:
            data = data[:-1]
        return data


class MerchantSettlementRecordRetrieveModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_data = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_data', 'merchant', 'level_name',
                  'account_name', 'account_bank', 'account_number', 'fail_reason', 'is_bind', 'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['level'] =  f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_data(self, obj):
        data = {}
        try:
            bill_list = []
            time_str = ''
            order_num = 0
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                bill_data = {}
                bill = merchantbillsettlementrecord.bill
                receipts_time = bill.receipts_time.strftime('%Y-%m-%d')
                time_str += f"{receipts_time},"
                orderinfo_set = bill.orderinfo_set.all()
                if orderinfo_set:
                    order_sum = orderinfo_set.count()
                    payable_settled_amount__sum = orderinfo_set.aggregate(Sum('payable_settled_amount'))['payable_settled_amount__sum']
                    order_num += order_sum
                    bill_data['order_count'] = order_sum
                    bill_data['payable_settled_amount__sum'] = payable_settled_amount__sum
                    bill_data['receipts_time'] = receipts_time
                    bill_data['bill_id'] = bill.id
                    bill_list.append(bill_data)
            if ',' in time_str:
                time_str = time_str[:-1]
            data['receipts_time'] = time_str
            data['order_count'] = order_num
            data['array'] = bill_list
        except:
            pass
        return data


class MerchantEightEightDrawListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'amount', 'received_time', 'state', 'state_str', 'business_no', 'level_name', 'mobile',
                  'merchant']

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_mobile(self, obj):
        try:
            mobile = obj.merchantuser.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''


class MerchantEightEightDrawRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    realname = serializers.SerializerMethodField(read_only=True)
    login_id = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'received_time', 'state', 'state_str', 'business_no', 'level',
                  'login_id', 'realname', 'amount', 'payment_no', 'mobile', 'merchant', 'return_msg', 'activity_name']

    def get_activity_name(self, obj):
        return '深圳达标商户有礼'

    def get_realname(self, obj):
        try:
            realname = obj.realname
            if realname:
                return f'{realname.replace(realname[-2], "*", 1)}'
            else:
                return ''
        except:
            return ''

    def get_login_id(self, obj):
        try:
            login_id = obj.login_id
            if login_id:
                if '@' in login_id:
                    return f'{login_id[:3]}****{login_id[login_id.find("@"):]}'
                else:
                    return f'{login_id[:3]}****{login_id[-4:]}'
            else:
                return ''
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data

    def get_mobile(self, obj):
        try:
            mobile = obj.merchantuser.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''


class MerchantBusinessQRCodeListModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant']

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data


class MerchantBusinessQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)
    manager = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant', 'manager', 'is_c_bind', 'is_c_bind_str', 'c_bind_time', 'customeruservice']

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_manager(self, obj):
        try:
            user = obj.user
            if user:
                nickname = user.nickname
                mobile = user.mobile
                if nickname:
                    nickname = f'{nickname.replace(nickname[-2], "*", 1)}'
                else:
                    nickname = ''
                if mobile:
                    mobile = f'{mobile[:3]}****{mobile[-4:]}'
                else:
                    mobile = ''
                return f'{nickname}({mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_customeruservice(self, obj):
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                realname = customeruservice.realname
                mobile = customeruservice.mobile
                if realname:
                    realname = f'{realname.replace(realname[-2], "*", 1)}'
                else:
                    realname = ''
                if mobile:
                    mobile = f'{mobile[:3]}****{mobile[-4:]}'
                else:
                    mobile = ''
                return f'{realname}({mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''


class UpdateStockUsableMerchantModelSerializer(serializers.ModelSerializer):

    user_nickname = serializers.SerializerMethodField(read_only=True)
    remark = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    wx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    ylx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    apply_state_str = serializers.CharField(source='get_apply_state_display', read_only=True)

    class Meta:
        model = UpdateStockUsableMerchant
        fields = ['id', 'user_nickname', 'file', 'remark', 'create_time', 'wx_is_enter', 'wx_is_enter_str', 'ylx_is_enter', 'ylx_is_enter_str',
                  'max_number', 'wx_entry_number', 'ylx_entry_number', 'apply_state', 'apply_state_str']

    def get_remark(self, obj):
        if obj.apply_state == 3:
            return obj.return_msg
        else:
            return obj.remark

    def get_user_nickname(self, obj):
        try:
            nickname = obj.user.nickname
            return f'{nickname.replace(nickname[-2], "*", 1)}'
        except:
            return ''


class MerchantEightEightActivityModelSerializer(serializers.ModelSerializer):

    activity_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level_name = serializers.SerializerMethodField(read_only=True)
    activity_status = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)

    class Meta:
        model = MerchantEightEightActivity
        fields = ['id', 'activity_id', 'activity_name', 'activity_start_time', 'activity_end_time', 'activity_description', 'level_name',
                  'activity_status', 'activity_status_str', 'total_amount', 'total_count', 'activity_type_str', 'activity_type']

    def get_activity_type(self, obj):
        if obj.id == 47:
            return 1
        elif obj.id == 50:
            return 4
        else:
            return obj.activity_type

    def get_activity_status(self, obj):
        if obj.activity_status == 1:
            if obj.activity_start_time < datetime.datetime.now():
                obj.activity_status = 2
                obj.save()
        elif obj.activity_status == 2:
            if obj.activity_end_time < datetime.datetime.now():
                obj.activity_status = 3
                obj.save()
        return obj.activity_status

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantEightEightWhiteTableModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightWhiteTable
        fields = ['id', 'merchant', 'business_no']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data


class MerchantEightEightActivityOrderModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    trade_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)

    class Meta:
        model = MerchantEightEightActivityOrder
        fields = ['id', 'merchant', 'business_no', 'is_standard', 'trade_amount', 'trade_time']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data


class CashActivityWhiteTableModelSerializer(serializers.ModelSerializer):

    add_user = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    add_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CashActivityWhiteTable
        fields = ('id', 'mobile', 'add_user', 'add_time', 'business_no', 'is_admin', 'merchant')

    def get_add_user(self, obj):
        if obj.is_admin == 1:
            return '管理员'
        else:
            return f'{obj.add_user.nickname.replace(obj.add_user.nickname[-2], "*", 1)}'

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['level_name'] = ''
        data['managermobile'] = ''
        data['managerName'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['managermobile'] = merchant.managermobile
                data['managerName'] = merchant.managerName
                data['merchant_name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data